package com.jackchong.net

import androidx.lifecycle.Lifecycle
import java.net.ConnectException
import java.net.NoRouteToHostException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.util.concurrent.ArrayBlockingQueue

/**
 * author : chong.huang
* create : 2/14/21
 * desc   :
 */
class AutoRetry : Retry{

    val queue = ArrayBlockingQueue<JNetParam<Any, JBaseData<Any>>>(100)

    override fun renet() {
        while (queue.isNotEmpty()) {
            val param = queue.poll()?: continue
            if (param.view.lifecycle().currentState != Lifecycle.State.DESTROYED) {
                JNet.net(param.api?: return, param)
            }
        }
    }

    override fun <T, J : JBaseData<T>> catchThrowableAdd(t: Throwable, param: JNetParam<T, J>) {
        if (!param.networkChangeAutoRetry) return
        when{
            t is UnknownHostException ||
            t is SocketTimeoutException ||
            t is NoRouteToHostException ||
            t is ConnectException -> {
                add(param)
            }
        }
    }

    override fun <T, J : JBaseData<T>> add(param: JNetParam<T, J>) {
        queue.offer(param.apply { cache.cancel() } as JNetParam<Any, JBaseData<Any>>)
    }

}